import { Link, useNavigate } from 'react-router-dom'
import { Card, Breadcrumb, Form, Button, Radio, Popconfirm, DatePicker, Select, Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from '@/assets/404.jpg'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import './index.scss'
import { useEffect, useState, } from 'react'
import { http } from '@/utils'
import { useStore } from '@/store/index'
import { observer } from 'mobx-react-lite'
const { Option } = Select
const { RangePicker } = DatePicker
function Article () {
  const { cannelStore } = useStore()
  // 获取频道列表并存储下拉框数据
  // const [channels, setChannels] = useState([])
  // // 发起下拉框数据请求
  // useEffect(() => {
  //   const getChannels = async () => {
  //     const { data: res } = await http.get(`/channels`)
  //     setChannels(res.channels)
  //   }
  //   // 调用获取下拉框数据请求
  //   getChannels()
  // }, [])
  // 文章列表数据管理
  const [dataCount, getdataCount] = useState({
    data_Count: 0,
    data_List: []
  })
  // 参数管理
  const [params, setParams] = useState({
    page: 1,
    per_page: 5,
  })
  // 获取文章列表数据
  const [UseStatus, setStatus] = useState(-1)
  useEffect(() => {
    const getAri = async () => {
      const { data: res } = await http.get(`/mp/articles`, { params })
      console.log(res)
      const { results, total_count } = res
      getdataCount({
        data_Count: total_count,
        data_List: results
      })
    }
    if (UseStatus.status === 1) {
      getAri()
    }
    getAri()
  }, [params, UseStatus])
  // 筛选数据
  const onSearch = (values) => {
    const { channel_id, status, date } = values
    setStatus(status)
    // console.log(values)
    // 只要引起params变化就会重新发起请求
    // 格式化表单数据
    const params1 = {}
    if (status !== -1) { params1.status = status }
    // if (status === -1) { params1.status = status }
    if (channel_id) { params1.channel_id = channel_id }
    if (date) {
      params1.begin_pubdate = date[0].format('YYYY-MM-DD')
      params1.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    setParams({
      ...params,
      ...params1
    })
  }
  // 监听页码变化
  const pageChange = (page) => {
    // 拿到当前页参数 修改params 引起接口更新
    setParams({
      ...params,
      page
    })
  }
  // 删除回调
  const delArticle = async (data) => {
    await http.delete(`/mp/articles/${data.id}`)
    // 更新列表
    setParams({
      page: 1,
      per_page: 5
    })
  }
  // 编辑事件跳转到发布文章页面
  const navigate = useNavigate()
  const compile = (data) => {
    navigate(`/publish?id=${data.id}`)
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 120,
      render: cover => {
        return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => <Tag color="green">审核通过</Tag>
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => compile(data)}
            />
            <Popconfirm
              title="确认删除该条文章吗?"
              onConfirm={() => delArticle(data)}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space >
        )
      }
    }
  ]
  return (
    <div>
      {/* 筛选区 */}
      <Card
        title={
          // 面包屑导航栏
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: 2 }} onFinish={onSearch}>
          {/* 选择状态区 */}
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {/* <Radio value={2}>全部</Radio> */}
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 下拉菜单 */}
          <Form.Item label="频道" name="channel_id">
            <Select
              placeholder="请选择文章频道"
              style={{ width: 120 }}
            >
              {cannelStore.Channel.map((item) => <Option key={item.id} value={item.id}>{item.name}</Option>)}
            </Select>
          </Form.Item>
          {/* 选择日期 */}
          <Form.Item label="日期" name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>
          <Form.Item>
            {/* 筛选按钮 */}
            <Button type="primary" htmlType="submit" style={{ marginLeft: 80 }} >
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* 表格区 */}
      <Card title={`根据筛选条件共查询到${dataCount.data_Count} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={dataCount.data_List}
          // 分页
          pagination={{
            position: ['bottomCenter'],
            // 总数据条数
            total: dataCount.data_Count,
            // 显示条数
            pageSize: params.per_page,
            // 切换页码事件
            onChange: pageChange
          }}
        />
      </Card>
    </div>
  )
}
export default observer(Article)